package com.mgq.netty.c8;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author MaGuangQi
 * @description echo 客户端
 * @date 2021-12-06 09:14
 **/
@Slf4j
public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture future = new Bootstrap().group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug("收到服务端发送的数据,{}",byteBuf.toString(StandardCharsets.UTF_8));
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        future.sync();
        Channel channel = future.channel();
        log.debug("请输入内容");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String s = scanner.nextLine();
            if ("q".equals(s)) {
                //关闭channel
                channel.close();
                break;
            }
            channel.writeAndFlush(Unpooled.copiedBuffer(s.getBytes(StandardCharsets.UTF_8)));
        }
        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("channel已经关闭完成,停止group..............");
                group.shutdownGracefully();
            }
        });
    }
}
